package com.bytecodezz.javacase.tools.decode;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * FileTools工具类
 * 将目标目录中的所有以 .tmp 结尾的文件，去除 .tmp，保持内容和文件结构不变
 * 
 * gradle文件代码为将对应文件加上 .tmp 后缀
 */
public class FileTools{

    public static void main(String[] args) {
        System.out.println("Task start ... ");
        long startTime = System.currentTimeMillis();
        fileRemoveTmp(new File("D:\\project\\VScode\\FileTools\\tempDir"),"D:\\project\\VScode\\FileTools\\tempDir\\root");    
        System.out.println("Tast finish. all time is "+ (System.currentTimeMillis() - startTime) + " ms");
       }

    public static void fileRemoveTmp(File  rootFile,String tmp){
        if (rootFile.isDirectory()){
            File[] files = rootFile.listFiles();
            for (File fileItem : files){
                fileRemoveTmp(fileItem, tmp + File.separator + rootFile.getName());
            }
            if (files == null || files.length == 0) {
                File fileEmptyDir = new File(tmp + File.separator + rootFile.getName());
                if (!fileEmptyDir.exists()) {
                    fileEmptyDir.mkdirs();
                }
            }
        }else{
            String filename = rootFile.getName(); 
            String lastName = filename.substring(filename.lastIndexOf("."));
            if (!lastName.equals(".tmp")){
                return;
            }
            try{
                InputStream inputStream = new FileInputStream(rootFile);
                byte[] bytes = inputStream.readAllBytes();
                inputStream.close();
                String fileNameNow = filename.substring(0,filename.lastIndexOf("."));
                File outFile = new File(tmp + File.separator + fileNameNow);
                if ( !outFile.getParentFile().exists()){
                    outFile.getParentFile().mkdirs();
                }
                FileOutputStream fileOutputStream = new FileOutputStream(outFile);
                fileOutputStream.write(bytes);
                fileOutputStream.flush();
                fileOutputStream.close();
            }catch(IOException e){
                System.out.println("IO error: "+e.getMessage());
            }
        }
    }
}